<?php
	include_once("../../backend/constant.php");
	$connection = new mysqli(dbhost, dblogin, dbpwd, database) or	die("Couldn't connect to database!");
	$connection->set_charset("utf8");
	date_default_timezone_set('Asia/Ho_Chi_Minh');
	session_start();
	$user = $_SESSION["loggedUser"];
	$userId = $_SESSION["loggedUserId"];
	if($_POST["ACTION"]=="POSTARTICLE"){
		$content = $_POST["txtContent"];
		$content = $connection->real_escape_string($content);
		$abstract = $_POST["txtAbstract"];
		$title = $_POST["txtTitle"];
		$tag = $_POST["txtTag"];
		$lang = $_POST["language"];
		
		$today = date("Y-m-d H:i:s");
		
		if($lang == 0)
			$result = $connection->query("insert into articles(userId,createdDate,title_vn,content_vn,abstract,tag, active) 
				values(".$userId.",cast('".$today."' as datetime),'".$title."','".$content."','" . $abstract ."','" . $tag ."',1)") or die("Query failed!");
		else
			$result = $connection->query("insert into articles(userId,createdDate,title_en,content_en,abstract,tag, active) 
				values(".$userId.",cast('".$today."' as datetime),'".$title."','".$content."','" . $abstract ."','" . $tag ."',1)") or die("Query failed!");
		
		//if(file_exists($_FILES['attach']['tmp_name'])) {
		if(isset($_FILES['attach']) && is_uploaded_file($_FILES['attach']['tmp_name'])) {
			$finfo = pathinfo($_FILES['attach']['name']);
			$ext = $finfo['extension']; // get the extension of the file
			$articleId = $connection->insert_id;
			$newname = "f". $articleId .".". $ext; 
			$target = '../../files/'.$newname;
			
			if(move_uploaded_file( $_FILES['attach']['tmp_name'], $target)){
				$furl = "";
				
				$mediatype = 0;
				if( ($ext == "png") || ($ext == "jpg") )
					$mediatype = 1;
				else if( ($ext == "mp3") || ($ext == "mmv") )
					$mediatype = 2;
				else if( ($ext == "mp4") || ($ext == "flv") )
					$mediatype = 3;
				
				$result = $connection->query("insert into media(userId,createdDate,mediatype,filename,url,article,active) 
					values(".$userId.",cast('".$today."' as datetime)," . $mediatype . ",'".$newname."','".$furl."'," . $articleId . ",1)") or die("Query failed!");
			}else
				print "{\"status\":\"FAILED\", \"error\":\"illegal file size or extension\"}";
			
		}
		
		if($result != false){
			print "{\"status\":\"OK\"}";
		}else{
			print "{\"status\":\"FAILED\"}";
		}
	}else if($_POST["ACTION"]=="UPDATEARTICLE"){
		$id = $_POST["id"];
		$content = $_POST["txtContent"];
		$content = $connection->real_escape_string($content);
		$abstract = $_POST["txtAbstract"];
		$title = $_POST["txtTitle"];
		$tag = $_POST["txtTag"];
		$isActive = $_POST["isActive"];
		$lang = $_POST["language"];
		
		//$today = date("Y-m-d H:i:s");
		//$sql = "update articles set title_vn='".$title."',content_vn=',abstract='"	.$abstract."',tag='".$tag."', active=".$isActive." where id=". $id;
		
		if($lang == 0)
			$result = $connection->query("update articles set title_vn='".$title."',content_vn='".$content."',abstract='"
				.$abstract."',tag='".$tag."', active=".$isActive." where id=". $id ) or die("{\"status\":\"FAILED\",\"query\":\"Syntax error\"}");
		else
			$result = $connection->query("update articles set title_en='".$title."',content_en='".$content."',abstract='"
				.$abstract."',tag='".$tag."', active=".$isActive." where id=". $id ) or die("{\"status\":\"FAILED\",\"query\":\"Syntax error\"}");
		
		/*
		if(file_exists($_FILES['attach']['tmp_name'])) {
			$finfo = pathinfo($_FILES['attach']['name']);
			$ext = $finfo['extension']; // get the extension of the file
			$articleId = $connection->insert_id;
			$newname = "f". $articleId .".". $ext; 
			$target = '../../files/'.$newname;
			
			if(move_uploaded_file( $_FILES['attach']['tmp_name'], $target)){
				$furl = "";
				
				$mediatype = 0;
				if( ($ext == "png") || ($ext == "jpg") )
					$mediatype = 1;
				else if( ($ext == "mp3") || ($ext == "mmv") )
					$mediatype = 2;
				else if( ($ext == "mp4") || ($ext == "flv") )
					$mediatype = 3;
				
				$result = $connection->query("insert into media(userId,createdDate,mediatype,filename,url,article,active) 
					values(".$userId.",cast('".$today."' as datetime)," . $mediatype . ",'".$newname."','".$furl."'," . $articleId . ",1)") or die("Query failed!");
			}else
				print "{\"status\":\"FAILED\", \"error\":\"illegal file size or extension\"}";
		}
		*/
		if($result != false){
			print "{\"status\":\"OK\"}";
		}else{
			print "{\"status\":\"FAILED\",\"query\":\"\"}";
		}
	}else if($_POST["ACTION"]=="SETACTIVE"){
		$id = $_POST["id"];
		$isActive = $_POST["isActive"];
		$result = $connection->query("update articles set active=" . $isActive . " where id=" . $id ) or die("{\"status\":\"FAILED\",\"query\":\"Syntax error\"}");
		if($result != false){
			print "{\"status\":\"OK\"}";
		}else{
			print "{\"status\":\"FAILED\",\"query\":\"\"}";
		}
	}else if($_POST["ACTION"]=="DELETEARTICLE"){
		$id = $_POST["id"];
		/*To delete an article, first I delete all comments and then files*/
		$connection->autocommit(false);
		$result = $connection->query("delete from comments where article=" . $id ) or die("{\"status\":\"FAILED\",\"query\":\"Syntax error\"}");
		$result = $connection->query("delete from media where article=" . $id ) or die("{\"status\":\"FAILED\",\"query\":\"Syntax error\"}");
		$result = $connection->query("delete from articles where id=" . $id ) or die("{\"status\":\"FAILED\",\"query\":\"Syntax error\"}");
		$connection->commit();	
		$connection->autocommit(true);
		if($result != false){
			print "{\"status\":\"OK\"}";
		}else{
			print "{\"status\":\"FAILED\",\"query\":\"\"}";
		}
	}else if($_POST["ACTION"]=="UPLOADFILE"){
		$finfo = pathinfo($_FILES['attach']['name']);
		$ext = strtolower( $finfo['extension'] ); // get the extension of the file
		$today = date("YmdHis");
		$newname = "f". $today .".". $ext; 
		$target = '../../files/'.$newname;
		if(move_uploaded_file( $_FILES['attach']['tmp_name'], $target)){
			$furl = "files/".$newname;
			
			$mediatype = 0;
			if( ($ext == "png") || ($ext == "jpg") || ($ext == "bmp") )
				$mediatype = 1;
			else if( ($ext == "mp3") || ($ext == "mmv") )
				$mediatype = 2;
			else if( ($ext == "mp4") || ($ext == "flv") )
				$mediatype = 3;
			
			$result = $connection->query("insert into media(userId,createdDate,mediatype,filename,url,article,active) 
				values(".$userId.",cast('".$today."' as datetime)," . $mediatype . ",'".$newname."','".$furl."',0,1)") or die("Query failed!");
			
			if($result != false){
				print "{\"status\":\"OK\",\"filename\":\"" . $_FILES['attach']['tmp_name'] .  "\"}";
			}else{
				print "{\"status\":\"FAILED\",\"errorMsg\":\"Database failed\"}";
			}
		}else
			print "{\"status\":\"FAILED\"}";
	}else if($_POST["ACTION"]=="DELETEFILE"){
		$fileId = $_POST["fileId"];
		
		$result = $connection->query("delete from media where id=".$fileId) or die("Query failed!");
		print "{\"status\":\"OK\"}";
	}
	$connection->close();
?>
